import { createRouter, createWebHistory } from 'vue-router'
import { getLocalToken } from '@/utils/auth'
import { ElMessage } from 'element-plus'
import LoginPage from '@/views/LoginPage/LoginPage.vue'
import LayoutPage from '@/views/LayoutPage.vue'
import HomePage from '@/views/HomePage/HomePage.vue'
import ArticlePage from '@/views/ArticlePage/ArticlePage.vue'
import PublicPage from '@/views/PublicPage/PublicPage.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/login', component: LoginPage },
    {
      path: '/',
      component: LayoutPage,
      children: [
        { path: '', component: HomePage },
        { path: '/article', component: ArticlePage },
        { path: '/publish/:id?', component: PublicPage },
      ],
    },
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = getLocalToken()
  if (to.path !== '/login' && !token) {
    ElMessage.error('登录信息已失效,请重新登录')
    return next('/login')
  }
  next()
})

export default router
